package main;

import BUS.*;
import DTO.DuLieuDTO;
import DTO.DuLieuThoDTO;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import Nhom7.mainPackage.main.*;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Spinner;
import android.widget.TextView;

public class main extends Activity implements
		AdapterView.OnItemSelectedListener, TextWatcher {
	/** Called when the activity is first created. */
	private EditText display;
	private EditText radiusText;
	private EditText filterText;

	private SearchEngine searchEngine;
	private final int maxResult = 10;
	private final int maxShow = 6;
	private ListView mlistView;
	private int index;
	private int indexshow;
	private Intent i;
	private double distance;
	private DuLieuThoDTO infoDTO;
	private boolean isClose = true;
	private LocationManager locationManager;
	private Location userLocation;
	private Location serviceLocation;
	private ImageButton previous;
	private ImageButton next;
	private boolean isRun;
	private int first = 0;
	private ArrayList<DuLieuDTO> listResult;
	private Utilities utilities;
	private String searchText;
	private Spinner selectOption;
	private ArrayList<DuLieuThoDTO> listinfoDTO;
	private static final String[] items = { "", "Theo Ten", "Theo Gia" };
	public static DuLieuThoDTO selectedItem;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		utilities = new Utilities();

		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		String provider = LocationManager.GPS_PROVIDER;
		userLocation = new Location("");
		userLocation.setLatitude(10.763788);
		userLocation.setLongitude(106.682293);
		LocationListener locationListener = new LocationListener() {

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub

			}

			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub

			}

			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub

			}

			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				userLocation.setLatitude(location.getLatitude());
				userLocation.setLongitude(location.getLongitude());
			}
		};
		locationManager
				.requestLocationUpdates(provider, 0, 0, locationListener);
		ImageButton load = (ImageButton) this.findViewById(R.id.searchButton);

		previous = (ImageButton) this.findViewById(R.id.previousbt);
		previous.setImageResource(R.drawable.go_previous_blue);
		next = (ImageButton) this.findViewById(R.id.nextbt);
		next.setImageResource(R.drawable.go_next_blue);
		load.setOnClickListener(new MyLoadAdapter());

		previous.setOnClickListener(new previousButton());
		next.setOnClickListener(new nextButton());
		display = (EditText) this.findViewById(R.id.editText1);
		radiusText = (EditText) this.findViewById(R.id.textradius);
		filterText = (EditText) this.findViewById(R.id.filterText);
		filterText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					if (!pressed) {
						pressed = true;
						index = 0;
						ShowList(showFilter());
						pressed = false;
					}
					return true;
				}
				return false;
			}
		});
		mlistView = (ListView) findViewById(R.id.listView1);
		mlistView.setOnItemLongClickListener(new itemClickLongListener());
		selectOption = (Spinner) this.findViewById(R.id.spinsort);
		display.addTextChangedListener(this);
		radiusText.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
			}

			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
			}

			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				isRun = false;
			}
		});
		selectOption.setOnItemSelectedListener(this);

		registerForContextMenu(mlistView);
		try {
			Context contex = this;
			searchEngine = new SearchEngine(contex);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	boolean pressed = false;

	public ArrayList<DuLieuThoDTO> showFilter() {
		ArrayList<DuLieuThoDTO> list = listinfoDTO;
		ArrayList<DuLieuThoDTO> temp = new ArrayList<DuLieuThoDTO>();
		// TODO Auto-generated method stub
		String text = filterText.getText().toString().toLowerCase();
		if (text.length() == 0) {
			return list;
		}

		for (DuLieuThoDTO duLieuThox : list) {
			String tenDicVu = utilities
					.FormatInputData(duLieuThox.TenDiaDiem());
			if (tenDicVu.indexOf(text) > -1) {
				temp.add(duLieuThox);
			}
		}

		return temp;
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		String helpSort = items[position];
		if (helpSort.compareTo("Theo Ten") == 0) {
			sortList(listinfoDTO);
			ShowList(listinfoDTO);
		}
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	class itemClickLongListener implements
			android.widget.AdapterView.OnItemLongClickListener {
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos,
				long Id) {
			// TODO Auto-generated method stub
			isRun = false;
			selectedItem = (DuLieuThoDTO) mlistView.getItemAtPosition(pos);
			return false;
		}
	}

	class MyLoadAdapter implements OnClickListener {

		public void onClick(View v) {
			try {
				loadText();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class nextButton implements OnClickListener {
		public void onClick(View v) {
			indexshow += maxShow;
			ShowList(listinfoDTO);
		}
	}

	class previousButton implements OnClickListener {
		public void onClick(View v) {
			if (indexshow - maxShow >= 0)
				indexshow -= maxShow;
			ShowList(listinfoDTO);
		}
	}

	public void loadText() throws IOException {
		isClose = false;

		index = 0;
		indexshow = 0;

		searchText = display.getText().toString();
		listResult = searchEngine.Search(searchText, 0, index);

		listinfoDTO = new ArrayList<DuLieuThoDTO>();
		int n = listResult.size();
		isRun = true;
		for (int i = 0; i < n; i++) {
			DuLieuDTO duLieu = listResult.get(i);
			serviceLocation = new Location("");

			infoDTO = searchEngine.getDuLieu(duLieu.MaDuLieu(),
					duLieu.MaDichVu(), duLieu.MaTenDiaDiem(), duLieu.SoNha(),
					duLieu.MaDuong(), duLieu.MaPhuong(), duLieu.MaQuanHuyen(),
					duLieu.KinhDo(), duLieu.ViDo());
			serviceLocation.setLatitude(infoDTO.ViDo());
			serviceLocation.setLongitude(infoDTO.KinhDo());
			distance = userLocation.distanceTo(serviceLocation);

			if (radiusText.getText().toString().compareTo("") == 0) {
				listinfoDTO.add(infoDTO);
			} else {
				double temp = Double.parseDouble(radiusText.getText()
						.toString()) * 1000;
				if (distance < temp) {
					listinfoDTO.add(infoDTO);
				}
			}
		}

		ShowList(listinfoDTO);

		Thread thread = new Thread() {
			@Override
			public void run() {

				while (isRun) {
					isClose = false;
					index += maxResult;
					listResult = searchEngine.FastSearch(index);
					if (listResult.size() < maxResult)
						isRun = false;
					int n = listResult.size();

					for (int i = 0; i < n; i++) {
						DuLieuDTO duLieu = listResult.get(i);
						serviceLocation = new Location("");

						infoDTO = searchEngine.getDuLieu(duLieu.MaDuLieu(),
								duLieu.MaDichVu(), duLieu.MaTenDiaDiem(),
								duLieu.SoNha(), duLieu.MaDuong(),
								duLieu.MaPhuong(), duLieu.MaQuanHuyen(),
								duLieu.KinhDo(), duLieu.ViDo());
						isClose = true;
						serviceLocation.setLatitude(infoDTO.ViDo());
						serviceLocation.setLongitude(infoDTO.KinhDo());
						distance = userLocation.distanceTo(serviceLocation);

						if (radiusText.getText().toString().compareTo("") == 0) {
							listinfoDTO.add(infoDTO);
						} else {
							double temp = Double.parseDouble(radiusText
									.getText().toString()) * 1000;
							if (distance < temp) {
								listinfoDTO.add(infoDTO);
							}
						}
					}
				}
			}
		};
		thread.stop();

		thread.start();

		ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, items);
		aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		selectOption.setAdapter(aa);

	}

	public void ShowList(ArrayList<DuLieuThoDTO> list) {

		ArrayList<DuLieuThoDTO> temp = new ArrayList<DuLieuThoDTO>();
		for (int i = 0; i < maxShow; i++) {
			if (indexshow + i < list.size())
				temp.add(list.get(indexshow + i));
		}

		mlistView.setAdapter(new ServiceItemAdapter(this,
				android.R.layout.simple_list_item_1, temp));

		next.setVisibility(View.VISIBLE);
		previous.setVisibility(View.VISIBLE);

	}

	public ArrayList<DuLieuThoDTO> sortList(ArrayList<DuLieuThoDTO> listResult) {
		Collections.sort(listResult, new ListSortByName());
		return listResult;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		new MenuInflater(this).inflate(R.menu.context_menu, menu);
		switch (selectedItem.MaDichVu()) {
		case 3:
		case 4:
		case 9:
		case 11:
			menu.findItem(R.id.menu).setEnabled(true);
			break;
		default:
			menu.findItem(R.id.menu).setEnabled(false);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		switch (item.getItemId()) {

		case R.id.map:
			i = new Intent(this, ViewMap.class);
			i.putExtra("Ten", selectedItem.TenDiaDiem());
			i.putExtra("DuLieu", selectedItem.MaDuLieu());
			i.putExtra("Vi_Do", selectedItem.ViDo());
			i.putExtra("Kinh_Do", selectedItem.KinhDo());

			startActivityForResult(i, 1);

			return true;
		case R.id.menu:
			i = new Intent(this, ViewMenu.class);

			i.putExtra("Ten", selectedItem.TenDiaDiem());
			i.putExtra("DuLieu", selectedItem.MaDuLieu());
			i.putExtra("Vi_Do", selectedItem.ViDo());
			i.putExtra("Kinh_Do", selectedItem.KinhDo());

			startActivityForResult(i, 1);

			return true;
		}
		return super.onContextItemSelected(item);
	}

	public void onAction() {

	}

	class ServiceItemAdapter extends ArrayAdapter<DuLieuThoDTO> {
		private ArrayList<DuLieuThoDTO> listduLieuThoDTO;

		ServiceItemAdapter(Context context, int textViewResourceId,
				ArrayList<DuLieuThoDTO> listduLieuThoDTO) {
			super(context, textViewResourceId, listduLieuThoDTO);
			this.listduLieuThoDTO = listduLieuThoDTO;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.listitem, null);
			}

			DuLieuThoDTO duLieuThoDTO = listduLieuThoDTO.get(position);
			if (duLieuThoDTO != null) {
				TextView info = (TextView) view.findViewById(R.id.info);
				TextView address = (TextView) view.findViewById(R.id.address);
				ImageView icon = (ImageView) view.findViewById(R.id.avatar);
				if (info != null) {
					switch (duLieuThoDTO.MaDichVu()) {
					case 1:
						icon.setImageResource(R.drawable.pic_hos);
						break;

					case 2:
						icon.setImageResource(R.drawable.pic_school);
						break;
					case 3:
						icon.setImageResource(R.drawable.pic_coffee);
						break;
					case 4:
						icon.setImageResource(R.drawable.pic_quan_an);
						break;
					case 5:
						icon.setImageResource(R.drawable.pic_atm);
						break;
					case 6:
						icon.setImageResource(R.drawable.pic_fuel_station);
						break;
					case 7:
						icon.setImageResource(R.drawable.pic_fashion_shop);
						break;
					case 8:
						icon.setImageResource(R.drawable.pic_barber);
						break;
					case 9:
						icon.setImageResource(R.drawable.pic_karaoke);
						break;
					case 10:
						icon.setImageResource(R.drawable.pic_res);
						break;
					case 11:
						icon.setImageResource(R.drawable.pic_hotel);
						break;
					case 12:
						icon.setImageResource(R.drawable.pic_park);
						break;
					case 13:
						icon.setImageResource(R.drawable.pic_market);
						break;
					case 14:
						icon.setImageResource(R.drawable.pic_cinema);
						break;
					case 15:
						icon.setImageResource(R.drawable.pic_football);
						break;
					case 16:
						icon.setImageResource(R.drawable.pic_bus_station);
						break;
					case 17:
						icon.setImageResource(R.drawable.pic_clinic);
						break;
					case 18:
						icon.setImageResource(R.drawable.pic_bus_station);
						break;
					case 19:
						icon.setImageResource(R.drawable.pic_football);
						break;
					case 20:
						icon.setImageResource(R.drawable.pic_hotel);
						break;
					case 21:
						icon.setImageResource(R.drawable.pic_market);
						break;
					case 22:
						icon.setImageResource(R.drawable.company);
						break;
					case 23:
						icon.setImageResource(R.drawable.pic_bus_station);
						break;
					case 24:
						icon.setImageResource(R.drawable.wood4);
						break;

					default:
						break;
					}
					info.setText(duLieuThoDTO.TenDiaDiem());

					address.setText(duLieuThoDTO.SoNha() + " "
							+ duLieuThoDTO.TenDuong() + ", P."
							+ duLieuThoDTO.TenPhuong() + ", Q."
							+ duLieuThoDTO.TenQuanHuyen());
				}
			}
			return view;
		}
	}

	public class ListSortByName implements Comparator<DuLieuThoDTO> {
		public int compare(DuLieuThoDTO o1, DuLieuThoDTO o2) {
			return o1.TenDiaDiem().compareTo(o2.TenDiaDiem());
		}
	}

	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		isRun = false;
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}
}